<?php

namespace api\components\behaviors;

use api\common\helpers\Constant;
use Yii;
use yii\base\Behavior;
use yii\web\UnauthorizedHttpException;
use api\traits\LoginTrait;

class BaseBehavior extends Behavior
{
    use LoginTrait;

    public function check()
    {
        /**
         * 先取用 header，后取 query 中的 token
         */
        $headers = Yii::$app->request->headers;
        $token = $headers['authorization'];
        if (empty($token)) {
            $token = Yii::$app->request->get('token');
        }

        if (Yii::$app->request->get('debug')) {
            return true;
        }

        if (!empty($headers['new_user'])) {
            return $this->loginByTokenNew($headers['authorization']);
        }

        /**
         * TODO:
         *   这里的 token 缓存应该用户中心统一设置、过期、删除
         *   目前这里设置会出现用户更新权限缓存未清除的现象
         */
        $userKey = Constant::LOGIN_USER_CACHE . '_' . $token;
        $cachedUser = Yii::$app->redis->get($userKey);

        if (empty($cachedUser) && !empty($token)) {
//            $cachedUser = $this->loginByToken($token);
            try {
                $cachedUser = $this->loginByToken($token);
            }catch (\Exception $e){
                return true;
            }
        }

        // openapi
        if (empty($cachedUser) && !empty($headers['appId'])) {
            $cachedUser = $this->getOpenApiUser();
        }

        if (!empty($cachedUser)) {
            return $this->checkUserRole($cachedUser);
        }

        throw new UnauthorizedHttpException('未登录，请先登录！');
        return true;
    }

    public function checkUserRole($user)
    {
        return true;
    }
}

